package edu.base.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.base.model.CatDetail;
import edu.base.model.Category;
import edu.base.model.Cmt;
import edu.base.model.CmtJoinUser;
import edu.base.model.Users;
import edu.base.service.CatDetailService;
import edu.base.service.CategoryService;
import edu.base.service.CmtService;
import edu.base.service.UsersService;
import edu.base.util.JsonResults;
import edu.base.util.PageUtil;

@Controller
@RequestMapping("/api")
public class ApiController {
	final static org.slf4j.Logger log = LoggerFactory.getLogger(AdminController.class);

	@Autowired
	UsersService usersService; 
	@Autowired
	CategoryService categoryService;
	@Autowired
	CmtService cmtService;
	@Autowired
	CatDetailService catDetailService;
	
	@RequestMapping("/users/name_query")
	@ResponseBody
	public JsonResults usersNameQuery(String loginName) {
		JsonResults res = new JsonResults();
		Map map = new HashMap<String,Object>();
		Users user = usersService.findByLoginName(loginName);
		
		if(user == null) {
			res.setResult_code(false);
		}else {
			user.setLoginPwd(null);
			res.setResult_code(true);
			map.put("user", user);
			res.setResult_arr(map);
		}
		return res;
	}
	
	@RequestMapping("cat/lst")
	@ResponseBody
	public JsonResults catLst(Integer pid) {
		JsonResults res = new JsonResults();
		Map map = new HashMap<String,Object>();
		map.put("arr", categoryService.query(pid));
		res.setResult_arr(map);
		return res;
	}
	
	@RequestMapping("catDetail/lst")
	@ResponseBody
	public JsonResults catDetailLst(Integer catId, Integer state,Boolean guoqi,Integer toId) {
		JsonResults res = new JsonResults();
		Map map = new HashMap<String,Object>();
		map.put("arr", catDetailService.find(catId, state, guoqi, toId));
		res.setResult_arr(map);
		return res;
	}
	
	@RequestMapping("cmt/add")
	@ResponseBody
	public JsonResults cmtAdd(String fk_type, Integer fk_id, String content, HttpSession session) {
		JsonResults res = new JsonResults();
		Cmt cmt = new Cmt();
		cmt.setFkType(fk_type);
		cmt.setFkId(fk_id);
		cmt.setContent(content);
		cmt.setUserId((Integer) session.getAttribute("user_id"));
		cmt.setCreateDate(new Date());
		cmtService.insert(cmt);
		
		return res;
	}
	
	@RequestMapping("demo")
	@ResponseBody
	public CatDetail demo(Integer id) {
		CatDetail item = catDetailService.findByKey(id);
		return item;
	}
	
	public static void main(String[] args) {
		System.out.println(Math.ceil((float)5/2));
	}
	
}
